<template>
  <d2-container>
    <div style="margin: 20px">

      <!--header-->
      <div style="margin: 10px 0">
        <el-input style="width: 200px" placeholder="请输入项目名称" suffix-icon="el-icon-search" v-model="project_name"
                  clearable></el-input>
        <el-button style="margin-left: 10px" type="primary" @click="getProjects">搜索</el-button>
        <el-button style="margin-left: 10px" type="primary" @click="reset">重置</el-button>
        <el-button style="float:right" type="primary" @click="$router.push('/project/create')">创建项目</el-button>
      </div>

      <!--table-->
      <div style="margin: 10px 0">
        <el-row v-for="item in projects" :key="item.id">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="color: #1E90FF;font-size: 10px">{{ item.type_name }} | </span>
              <span>{{ item.name }}</span>
              <el-popconfirm popper-class="popper" title="确认删除该项目吗?"
                             @confirm="deletePro(item.id,item.children)">
                <el-button style="float: right; margin-left:10px; padding: 5px 0; color: rgba(197,69,102,0.68)"
                           type="text" slot="reference">删除
                </el-button>
              </el-popconfirm>
              <el-button style="float: right; padding: 5px 0" type="text" @click="startTrain(item.id)">训练
              </el-button>
              <div style="font-size: 10px; color: #c5c9ce; margin-top: 5px">{{ item.description }}</div>
            </div>

            <el-table :data="item.children" border stripe>
              <el-table-column prop="name" label="模型名称">
                <!--                <template slot-scope="scope">{{ scope.row.name | nameFilter }}</template>-->
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
              <el-table-column prop="version" label="版本" width="70px"></el-table-column>
              <el-table-column prop="status_name" label="训练状态" width="130px"></el-table-column>
              <el-table-column prop="time" label="训练时长" width="130px">
                <template v-if="scope.row.status===2" slot-scope="scope">{{ scope.row.time + ' 时' }}</template>
              </el-table-column>
              <el-table-column prop="result" label="模型效果">
                <template slot-scope="scope">
                  <el-button :disabled="scope.row.status !== 2" type="text" style="padding: 5px 0"
                             @click="$router.push({path:'/model/report',query:{ id:scope.row.id }})">
                    评估报告
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="operation" label="操作">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.status === 1" type="text" style="padding: 5px 0;margin-right: 10px;"
                             @click="openTrainingProcess()">
                    查看实时训练过程
                  </el-button>
                  <el-button :style="{ display: scope.row.status!==2?'none':'' }" type="text" style="padding: 5px 0"
                             @click="$router.push({path:'/model/test',query:{ id:scope.row.id }})">
                    模型测试
                  </el-button>
                  <el-button :style="{ display: scope.row.is_published || scope.row.status !== 2 ? 'none' : '' }"
                             type="text" style="padding: 5px 0"
                             @click="publishService(scope.row.name, item.type, item.id, scope.row.id)">
                    服务发布
                  </el-button>
                  <el-popconfirm popper-class="popper" title="确认删除该模型吗?" @confirm="deleteModel(scope.row.id)">
                    <el-button :style="{ display: scope.row.status===2?'':'none' }"
                               style="margin-left: 10px; padding: 5px 0; color: rgba(197,69,102,0.68)" type="text"
                               slot="reference">
                      模型删除
                    </el-button>
                  </el-popconfirm>
                  <el-popconfirm popper-class="popper" title="确认删除该模型吗?" @confirm="deleteModel(scope.row.id)">
                    <el-button :style="{ display: scope.row.status===3?'':'none' }"
                               style="color: rgba(197,69,102,0.68); padding: 5px 0" type="text" slot="reference">
                      模型删除
                    </el-button>
                  </el-popconfirm>
                  <el-button :style="{ display: scope.row.status===1?'':'none' }"
                             style="color: rgba(197,69,102,0.68); padding: 5px 0" type="text"
                             @click="stopTrain(scope.row.id)">
                    终止训练
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-row>
      </div>

      <!-- 分页插件 -->
      <div style="margin: 10px 0">
        <el-card class="card" v-if="totalPage > 0">
          <div>
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[1, 2, 3]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalPage">
            </el-pagination>
          </div>
        </el-card>
      </div>

    </div>
  </d2-container>
</template>

<script>
import {GetProList, DelProObj, DelModelObj, StopTrain, GetModelList, GetTrainStatus, PublishService} from './api.js'
import {Loading} from 'element-ui'

export default {
  name: 'index',
  data() {
    return {
      projects: [],
      models: [],
      project_name: '',
      totalPage: 0,
      currentPage: 1,
      pageSize: 3,
      timerArr: []
    }
  },
  filters: {
    nameFilter(value) {
      return value.substring(0, value.length - 36)
    }
  },
  methods: {
    // 获取所有项目
    getProjects() {
      const query = {name: this.project_name, creator_id: this.$store.state.d2admin.user.info.user_id}
      query.limit = this.pageSize
      query.page = this.currentPage
      GetProList(query).then(response => {
        this.totalPage = response.data.total
        this.currentPage = response.data.page
        this.projects = response.data.data
      })
    },
    // 重置搜索框
    reset() {
      this.project_name = ''
      this.getProjects()
    },
    // 删除项目
    deletePro(id, children) {
      for (let i = 0; i < children.length; i++) {
        if (children[i].status === 1) {
          this.$message.error('项目下有模型正在训练，无法删除！')
          return
        }
      }
      DelProObj(id).then(response => {
        this.$message.success('删除项目成功！')
        this.getProjects()
      }).catch(error => {
        this.$message.error('删除项目失败！')
        console.log(error)
      })
    },
    // 删除模型
    deleteModel(id) {
      DelModelObj(id).then(response => {
        this.$message.success('删除模型成功！')
        this.getProjects()
      }).catch(error => {
        this.$message.error('删除模型失败！')
        console.log(error)
      })
    },
    // 开始训练
    startTrain(id) {
      for (let i = 0; i < this.models.length; i++) {
        if (this.models[i].status === 1) {
          this.$message.error('已有模型正在训练')
          return
        }
      }
      this.$router.push({path: '/model/train', query: {id: id}})
    },
    // 终止训练
    stopTrain(id) {
      // 启动loading服务
      const loadingInstance = Loading.service({
        target: document.getElementById('detailClass'),
        fullscreen: true,
        text: '已提交终止训练，请稍候...',
        background: 'rgba(225,225,225,0.8)'
      })
      StopTrain(id).then(response => {
        console.log(response)
        // 关闭loading
        loadingInstance.close()
        this.$message.success('终止训练成功')
        this.getProjects()
      })
    },
    // 查看训练进度
    openTrainingProcess() {
      const tensorboardUrl = 'http://localhost:6006';
      window.open(tensorboardUrl, '_blank');
    },
    // 发布服务
    publishService(modelName, type, projectID, modelID) {
      const obj = {
        name: modelName,
        type: type,
        project: projectID,
        model: modelID,
        status: 0
      }
      PublishService(obj).then(response => {
        this.$message.success('服务发布成功')
        this.getProjects()
      }).catch(error => {
        console.log(error)
        this.$message.error('服务发布失败')
      })
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val
      this.getProjects()
    },
    // 翻页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getProjects()
    },
    // 轮询
    createSetInterval(id, num) {
      console.log('status search')
      console.log(id)
      // 轮询超过3次停止
      if (num >= 2) {
        for (let i = 0; i < this.timerArr.length; i++) {
          if (this.timerArr[i].value === id) {
            window.clearInterval(this.timerArr[i].timer)
            this.timerArr.splice(i, 1)
            break
          }
        }
        return
      }
      GetTrainStatus(id).then((response) => {
        if (response.data === 0 || response.data === 2 || response.data === 3) { // 0未训练 2训练完成 3训练终止
          this.getProjects()
          for (let i = 0; i < this.timerArr.length; i++) {
            if (this.timerArr[i].value === id) {
              window.clearInterval(this.timerArr[i].timer)
              this.timerArr.splice(i, 1)
              break
            }
          }
        }
      })
    }
  },
  created: function () {
    this.getProjects()
  },
  mounted() {
    const query = {creator_id: this.$store.state.d2admin.user.info.user_id}
    GetModelList(query).then(response => {
      this.models = response.data.data
      this.timerArr = []
      for (let i = 0; i < response.data.data.length; i++) {
        if (response.data.data[i].status === 1) {
          let num = 0
          const data = {
            timer: window.setInterval(() => {
              setTimeout(() => {
                this.createSetInterval(response.data.data[i].id, num++)
              }, 1)
            }, 5000),
            value: response.data.data[i].id
          }
          this.timerArr.push(data)
        }
      }
    })
  },
  // 销毁计时器
  destroyed() {
    for (let i = 0; i < this.timerArr.length; i++) {
      clearInterval(this.timerArr[i].timer)
    }
  }
}
</script>

<style lang="scss">
.box-card {
  width: 100%;
  margin-bottom: 10px;
}

//分页底部
.card {
  position: fixed;
  bottom: 0;
  height: 60px;
  margin: auto;
}

//气泡框
.popper {
  width: 190px;
  height: 100px;
  box-shadow: 0px 2px 10px 0px rgba(51, 70, 84, 0.2);

  .el-popconfirm__main {
    width: 100%;
    height: 20px;
    font-size: 15px;
    font-weight: 500;
    text-align: left;
    color: #333333;
    line-height: 20px;
    margin: 10px 0 12px 0;
    padding-left: 9px;
  }

  .el-popconfirm__action {
    padding-left: 10px;
    // 交换 确定 和 取消 按钮的位置
    .el-button:nth-child(1) {
      float: right;
      margin-right: 10%;
      width: 55px;
      background: #ffffff;
      border: 1px solid;
      border-radius: 6px;
      height: 28px;
      text-align: center;
    }

    .el-button:nth-child(2) {
      float: left;
      margin-left: 10%;
      width: 55px;
      border-radius: 6px;
      height: 28px;
      text-align: center;
    }
  }
}
</style>
